<?php

namespace App\Http\Controllers\Account;

use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Account\UserGroup;
use App\Helpers\Code;

class UserGroupController extends Controller
{

    public function __construct()
    {
        $this->rules = [
            'title' => 'bail|required|unique:user_groups|max:50',
            'description' => 'max:100',
            'abbreviation' => 'bail|required|unique:user_groups|max:50'
        ];

        $this->messages = [
            'title.required' => trans('user.usergroup.title_required'),
            'title.unique' => trans('user.usergroup.title_unique'),
            'title.max' => trans('user.usergroup.title_max'),
            'description.max' => trans('user.usergroup.description_max'),
            'abbreviation.required' => trans('user.usergroup.abbreviation_required'),
            'abbreviation.unique' => trans('user.usergroup.abbreviation_unique'),
            'abbreviation.max' => trans('user.usergroup.abbreviation_max'),
        ];

        $this->model = new UserGroup();
    }

    public function addUsergroup(Request $request)
    {
        try {
            $data = $request->only($this->model->getFillable());

            $validator = Validator::make($data, $this->rules, $this->messages);

            if ($validator->fails()) {
                return $this->error($validator, Code::SYSTEM_VALIDATOR_ERROR);
            }

            $this->result['data'] = $this->model->addUsergroup($data);

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function deleteUsergroup($id)
    {
        try {
            $model = $this->model->deleteUsergroup($id);

            $this->checked($model, [
                'null' => 'common.delete_failure',
                Code::INSIDE_EXIST_DEPENDENCE => 'user.usergroup.delete_failure_dependence'
            ]);

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function editUsergroup($id, Request $request)
    {
        try {
            $rules = [];
            
            $data = $request->only(array_diff($this->model->getFillable(), ['data_scope']));

            foreach ($data as $key => $value) {
                switch ($key) {
                    case 'title':
                        $rules['title'] = ['bail', 'required', 'max:50', \Illuminate\Validation\Rule::unique('user_groups')->ignore($id)];
                        break;
                    case 'abbreviation':
                        $rules['abbreviation'] = ['bail', 'required', 'max:50', \Illuminate\Validation\Rule::unique('user_groups')->ignore($id)];
                        break;
                    default :
                        $rules[$key] = $this->rules[$key];
                }
            }

            $validator = Validator::make($data, $rules, $this->messages);

            if ($validator->fails()) {
                return $this->error($validator, Code::SYSTEM_VALIDATOR_ERROR);
            }

            $model = $this->model->editUsergroup($id, $data);

            $this->checked($model, ['null' => 'common.edit_failure']);

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function getUsergroupList(Request $request)
    {
        try {
            $search = $this->handleSearch($request, $this->model);

            $limit = (int) $request->input('limit');

            $sorter = $this->handleSort($request, $this->model->sorters);

            return preprocess($this->model->getUsergroupList($limit, $sorter, $search));
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function getUsergroupListAll()
    {
        try {
            $this->result['data'] = $this->model->getUsergroupListAll();
            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function getUsergroupPermissionList($id)
    {
        try {
            $model = $this->model->getUsergroupPermissionList($id);

            $this->checked($model, ['null' => 'common.get_failure']);

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function editUsergroupPermission($id, Request $request)
    {
        try {
            if (!$request->has('permission')) {
                return $this->error('user.usergroup.permission_required');
            }

//        $data = explode(',', $request->input('permission'));
            $data = $request->input('permission');

            $permissions = is_array($data) ? array_unique(array_filter($data)) : [];
            $model = $this->model->editUsergroupPermission($id, $permissions);

            $this->checked($model, ['null' => 'common.edit_failure', Code::INSIDE_EXIST_DEPENDENCE => 'common.edit_failure']);

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function getUsergroupMenuList($id)
    {
        try {
            $model = $this->model->getUsergroupMenuList($id);

            $this->checked($model, ['null' => 'common.get_failure']);

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function editUsergroupMenu($id, Request $request)
    {
        try {
            if (!$request->has('menu')) {
                return $this->error('user.usergroup.menu_required');
            }

            $data = $request->input('menu');

            $menus = is_array($data) ? array_filter($data) : [];

            $model = $this->model->editUsergroupMenu($id, $menus);

            $this->checked($model, ['null' => 'common.edit_failure', Code::INSIDE_EXIST_DEPENDENCE => 'common.edit_failure']);

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    /**
     * 获取指定用户组下的用户
     * @param $id
     * @param Request $request
     * @return array
     */
    public function getUsergroupUserList($id, Request $request)
    {
        try {
            $limit = (int) $request->input('limit');

            $model = $this->model->getUsergroupUserList($id, $limit);

            if ($model === null) {
                return $this->error('common.get_failure');
            }

            return preprocess($model);
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function getUsergroup($id)
    {
        try {
            $model = $this->model->getUsergroup($id);

            $this->checked($model, ['null' => 'common.get_failure']);

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    /**
     * 获取指定用户组下指定菜单的功能
     * @param $id       group_id
     * @param $menuId     menu_id
     * @return array
     */
    public function getUsergroupMenuActionAll($id, $menuId)
    {
        try {
            $model = $this->model->getUsergroupMenuActionAll($id, $menuId);

           $this->result['data'] = $model;

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    /**
     * 编辑指定用户组下指定菜单的功能
     * @param $id
     * @param $menuId
     * @param Request $request
     * @return array
     */
    public function editUsergroupMenuAction($id, $menuId, Request $request)
    {
        try {
            if (!$request->has('actions')) {
                return $this->error('user.usergroup.action_necessarily');
            }

            $actions = $request->input('actions');
            if (!is_array($actions) && count($actions) < 1) {
                return $this->error('common.data_format_error');
            }

            foreach ($actions as $k => $v) {
                if(count(array_diff(array_keys($v), ['action_id', 'scope_id'])) > 0 || count(array_diff(['action_id', 'scope_id'], array_keys($v))) > 0) {
                    return $this->error('common.data_format_error');
                }
            }

            $actionIds = array_column($actions, 'action_id');

            if (count($actionIds) != count($actions)) {
                return $this->error('common.data_format_error');
            }

            $model = $this->model->editUsergroupMenuAction($id, $menuId, $actions);

            $this->checked($model, [
                Code::INSIDE_ERROR_1 => 'user.usergroup.action_scope_not_exists',
                Code::INSIDE_ERROR_2 => 'user.usergroup.menu_action_not_exists',
                Code::INSIDE_ERROR_3 => 'user.usergroup.user_group_and_menu_not_exists',
                Code::INSIDE_DATABASE_ERROR => 'common.database_error',
            ]);

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function getUsergroupMenuSelected($id)
    {
        try {
            $model = $this->model->getUsergroupMenuSelected($id);

            $this->checked($model, ['null' => 'common.recored_not_found']);

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

}
